package at.tuwien.seminar.scrum1.proxies;

import java.util.List;

import javax.persistence.EntityManager;

import at.tuwien.seminar.scrum1.hibernate.HibernateUtil;
import at.tuwien.seminar.scrum1.model.Customer;

public class CustomerProxy {
	
	private static CustomerProxy instance;
	private EntityManager em;

	private CustomerProxy() {
		em = HibernateUtil.getEntityManagerFactory().createEntityManager();
	}

	public static CustomerProxy getInstance() {
		return instance == null ? instance = new CustomerProxy() : instance;
	}

	public List<Customer> getAll() {
       	
		return getAll(em);
	}
	
	public List<Customer> getAll(EntityManager em) {
       	return (List<Customer>)em.createQuery("from Customer").getResultList();     
	}
	
	public Customer getById(Long id){
		List<Customer> customers= em.createQuery("from Customer WHERE id=:id", Customer.class).setParameter("id", id).getResultList();
		
		if(!customers.isEmpty())
			return customers.get(0);
		else
			return null;
	}
	
	public long insertCustomer(Customer customer)
	{
		return insertCustomer(customer,em);
	}
	
	public long insertCustomer(Customer customer, EntityManager em)
	{
		em.getTransaction().begin();
		em.persist(customer);
		em.getTransaction().commit();
		
		return customer.getId();
	}
	
	public Customer updateCustomer(Customer customer)
	{
		return updateCustomer(customer,em);
	}
	
	public Customer updateCustomer(Customer customer, EntityManager em)
	{
		em.getTransaction().begin();
		em.merge(customer);
		em.getTransaction().commit();
		
		return customer;
	}


    public void deleteCustomer(Customer customer) {
        deleteCustomer(customer,em);
    }

    public void deleteCustomer(Customer customer, EntityManager em) {
        em.getTransaction().begin();
		em.remove(customer);
		em.getTransaction().commit();
    }


    public Long extractId(String name) {
        return Long.parseLong(name.substring(name.indexOf("[")+1, name.length()-1));
    }
}
